package itheima03;
/*
    递归求和
    假设定义求和方法: getSum(int n)
    求1到n的和?

    先通过求1到5的和,找规律
    getSum(5) = 5 + 4 + 3 + 2 + 1
            = 5 + getSum(4)
                getSum(4) = 4 + 3 + 2 + 1
                    = 4 + getSum(3)
                        getSum(3) = 3 + 2 + 1
                            = 3 + getSum(2)
                                getSum(2) = 2 + 1
                                    = 2 + getSum(1)
                                        getSum(1): 1
    总结:
        1.规律:
            getSum(5) = 5 + getSum(4) = 5 + getSum(5-1)
            getSum(n) = n + getSum(n-1)
        2.出口:
            getSum(1): 1
            if(n==1) {
                return 1;
            }
 */
public class Demo02DiGuiSum {
    public static void main(String[] args) {
        //调用方法
        int sum = getSum(4);
        System.out.println(sum);
    }
    //定义求和方法: 递归调用
    public static int getSum(int n) {
        //2.出口:
        if(n==1) {
            return 1;
        }
        //1.规律
        return n + getSum(n-1);//4+3+2+1
    }
}
